package com.xls.box2023.home;

import android.text.TextUtils;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.lzz.bottomencapsulation.eventbus.MessageEvent;
import com.lzz.bottomencapsulation.net.RequestCallBack;
import com.lzz.bottomencapsulation.utils.AppUtils;
import com.lzz.bottomencapsulation.utils.TUtils;
import com.xls.box2023.Consts.EventCode;
import com.xls.box2023.adapter.YouXiListAdapter;
import com.xls.box2023.dialog.UserRegErrorDialog;
import com.xls.box2023.entity.AccountBalanceEntity;
import com.xls.box2023.entity.UserEntity;
import com.xls.box2023.entity.YouXiEntity;
import com.xls.box2023.login.LoginNetworkUtil;
import com.xls.box2023.login.LoginUtil;
import com.xls.box2023.manager.APKDownLoadEntity;
import com.xls.box2023.manager.APKDownLoadManager;
import com.xls.box2023.mvp.BasePresenterImpl;
import com.xls.box2023.network.CallbackT;
import com.xls.box2023.utils.SPUtils;
import com.xls.box2023.utils.VersionUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.recyclerview.widget.RecyclerView;

/**
 * MVPPlugin
 */

public class  HomePresenter extends BasePresenterImpl<HomeContract.View> implements HomeContract.Presenter{
    private YouXiListAdapter youXiListAdapter;
    private ArrayList<YouXiEntity> youXiListData=new ArrayList<>();
    private HashMap<Long,YouXiEntity> youXiListData2=new HashMap<>();
    @Override
    public RecyclerView.Adapter getYouXiListAdapter() {
        if (youXiListAdapter==null){
            youXiListAdapter=new YouXiListAdapter(activity, youXiListData);
        }
        return youXiListAdapter;
    }

    @Override
    public void onRefresh() {
        youXiListData.clear();
        youXiListData2.clear();
        youXiListAdapter.notifyDataSetChanged();
        getAccountBalance();
    }

    @Override
    public void onLoadMore() {

    }


    /**
     * 停止文件下载
     */
    @Override
    public void stopDownloadFile() {
        APKDownLoadManager.getInstance().stopAll();
        DownloadApkUtils.getInstance().stopAllDownloadFile();
    }

    /**
     * 获取积分数据，该接口服务器会创建用户，所以  获取用户信息需要放在接口成功请求之后
     */
    @Override
    public void getAccountBalance() {
        //        获取积分及金币数额
        HomeNetWorkUtil.getInstance().getAccountBalance(new RequestCallBack<AccountBalanceEntity>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onStop() {
            }

            @Override
            public void onRequestSuccess(AccountBalanceEntity requestData) {
                if (getView()==null||context==null||requestData==null)return;
                getView().showNum(requestData);
                getMyApps();
            }

            @Override
            public void onRequestfail(String errno, String errmsg) {
                mView.showShareBtn(false);
            }
        });
    }

    @Override
    public void fkCheck(Map<String, String> stringStringMap) {
        LoginNetworkUtil.getInstance().fkCheck(activity,"box_home",stringStringMap, new RequestCallBack<String>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onStop() {

            }

            @Override
            public void onRequestSuccess(String requestData) {

            }

            @Override
            public void onRequestfail(String errno, String errmsg) {

            }
        });
    }
    @Override
    public void getPermissions() {
        XXPermissions.with(activity)
                // 申请单个权限
                .permission(Permission.READ_PHONE_STATE)
                .permission(Permission.READ_MEDIA_IMAGES)
                .permission(Permission.READ_PHONE_NUMBERS)
                .permission(Permission.READ_MEDIA_AUDIO)
                .permission(Permission.READ_MEDIA_VIDEO)
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            userReg();//绑定关系
                            LoginNetworkUtil.getInstance().getLoginParams2(activity, new CallbackT<Map<String, String>>() {
                                @Override
                                public void callback(Map<String, String> stringStringMap) {
                                    stringStringMap.put("appName", AppUtils.getPackageName(activity));
                                    stringStringMap.put("token",SPUtils.getLoginToken());
                                    fkCheck(stringStringMap);
                                }
                            });
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            XXPermissions.startPermissionActivity(activity, permissions);
                        } else {
                            TUtils.showShort(context,"请授予权限,并重新登陆");
                            LoginUtil.getInstance().outLogin(activity);
                        }
                    }
                });
    }

    @Override
    public void getAppShareButtion() {
        LoginNetworkUtil.getInstance().getAppShareButtion(activity, new RequestCallBack<String>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onStop() {

            }

            @Override
            public void onRequestSuccess(String requestData) {
                mView.showShareBtn(true);
            }

            @Override
            public void onRequestfail(String errno, String errmsg) {
                mView.showShareBtn(false);
            }
        });
    }

    @Override
    public void userReg() {
        LoginNetworkUtil.getInstance().userReg(activity, com.xls.box2023.utils.SPUtils.getunId(), new RequestCallBack<String>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onStop() {

            }

            @Override
            public void onRequestSuccess(String requestData) {
                getUser();
            }

            @Override
            public void onRequestfail(String errno, String errmsg) {
                getUser();
            }
        });
    }

    @Override
    public void refishAPPData(MessageEvent messageEvent) {
        if (messageEvent.getCode()== EventCode.code_state_chanage
                &&messageEvent.getData() instanceof APKDownLoadEntity){
            APKDownLoadEntity youXiEntity=((APKDownLoadEntity) messageEvent.getData());
            YouXiEntity youXi=youXiListData2.get(youXiEntity.getAppid());
            youXiListAdapter.notifyItemChanged(youXi.getPosition()+1,youXiEntity);
        }
    }

    /**
     * 显示无关系  或绑定关系失败的弹窗
     */
    public void showuserRegErrorDialog() {
        UserRegErrorDialog userRegErrorDialog=new UserRegErrorDialog(context);
        userRegErrorDialog.show();
    }


    private void getUser() {
        //        获取用户信息
        HomeNetWorkUtil.getInstance().getUserInfo(new RequestCallBack<UserEntity>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onStop() {

            }

            @Override
            public void onRequestSuccess(UserEntity requestData) {
                if (getView()==null||context==null||requestData==null)return;
                getView().showUserInfo(requestData);
                SPUtils.saveUserInFo(requestData);
                if (TextUtils.isEmpty(requestData.getRefferId1())&&TextUtils.isEmpty(requestData.getRefferId2())){
                    showuserRegErrorDialog();
                }else {
                    getAppShareButtion();
                    VersionUtil.getInstance().checkUpdate(activity);
                    getAccountBalance();
                }
            }

            @Override
            public void onRequestfail(String errno, String errmsg) {

            }
        });
    }

    private void getMyApps() {
        //        获取游戏列表
        HomeNetWorkUtil.getInstance().getMyApps(new RequestCallBack<ArrayList<YouXiEntity>>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onStop() {
                if (getView()==null||context==null)return;
                mView.getStateView().showContentView();
                mView.stopRefishView();
            }

            @Override
            public void onRequestSuccess(ArrayList<YouXiEntity> requestData) {
                if (getView()==null||context==null)return;

                if (requestData==null){
                    mView.getStateView().showEmptyView();
                    return;
                }
//                for (YouXiEntity youXiEntity:requestData){
//                    for (Long appid:DownloadApkUtils.getInstance().downloadUtils.keySet()){
//                        if (appid==youXiEntity.getAppId()){
//                            youXiEntity.setDownloadUrl(DownloadApkUtils.getInstance().downloadUtils.get(appid).getUrl());
//                        }
//                    }

//                }
                youXiListData.clear();
                youXiListData2.clear();
                for (int i=0;i<requestData.size();i++){
                    YouXiEntity youXi=requestData.get(i);
                    youXi.setPosition(i);
                    youXiListData2.put(youXi.getAppId(),youXi);
                }
                youXiListData.addAll(requestData);
                youXiListAdapter.notifyDataSetChanged();
                if (youXiListData.size()==0){
                    mView.getStateView().showEmptyView();
                }
            }

            @Override
            public void onRequestfail(String errno, String errmsg) {
                mView.getStateView().showErrorView();
            }
        });
    }
}
